
class DivGraph < Pan::Component
  @@graph_no = 0
  def initialize(title,data=nil,width=370, height=200)
    @title = title
    @data = data || [[1,200],[2,197],[3,175],[4,166],[5,105],[6,100],[7,95],[8,73],[9,55],[10,35]]
    @width = width
    @height = height
    @no = @@graph_no
    @@graph_no += 1
  end

  def initial_hours
    @data.first[1]
  end

  def render_pre(html)
    html.text <<EOS
<script type="text/javascript" src="/js/wz_jsgraphics.js"></script>
<script type="text/javascript" src="/js/line.js"></script>
<div id="graphCanvas#{@no}" class="graph" style="overflow: auto; position:relative;height:#{@height}px;width:#{@width}px;"></div>
<script>
var g = new line_graph();
var g2 = new line_graph();
EOS
  end
  
  def render_post(html)
    html.text <<EOS
g.setMax(#{initial_hours+10});
g.setColor(1);
g2.setMax(#{initial_hours+10});
g2.setColor(2);
g.dotColor = "red";
g.render("graphCanvas#{@no}", "#{@title}", 150);
g2.dotColor = "#b5b5b5";
g2.render("graphCanvas#{@no}", "",150);
</script>
EOS
  end
  
  def render_on(html)
    render_pre(html)
    @data.each do |label, value|
      html.text("g.add('#{label}', #{value});") if value and value > 0
    end
    html.text("\n")
    labels = @data.map{|ea| ea.first}
    step = initial_hours / @data.size.to_f
    values = (1..@data.size).to_a.map{|ea| (ea*step).to_i}.reverse
    labels.zip(values).each do |label, value|
      html.text("g2.add('#{label}', #{value});")
    end
    render_post(html)
  end
end
